package com.okok.controller;

import java.text.ParseException;

import com.common.ActionResult;
import com.common.Const;
import com.okok.dto.UserDTO;
import com.okok.entity.User;
import com.okok.service.AccountService;
import com.okok.service.TokenService;
import com.okok.service.UserService;
import com.shiro.entity.Token;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 个人信息相关api
 * 
 * reg:注册账户
 * 
 * login:登陆
 * 
 * logout:登出
 * 
 * @author Eason
 *
 */
@Controller
@RequestMapping(value = "/api/profile")
public class ProfileController {

	private static Logger logger = LoggerFactory.getLogger(ProfileController.class);
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private TokenService tokenService;
	
//	@Autowired
//	private UserService userService;
/*
	@Autowired
	private AuthcodeService authcodeService;
	
	@SuppressWarnings("unused")
	@Autowired
	private MailService mailService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private AuthService authService;
	
	@Autowired
	private RongyunService rongyunService;*/
	
	/**
	 * 登陆
	 * 
	 * 逻辑：
	 * 1， 注册登陆事件
	 * 2， 根据userid  和password 跟后台比对。
	 * 3， 返回信息
	 * 
	 * @param sequence
	 * @param loginName
	 * @return
	 */
	@RequestMapping(value="login.action", method = RequestMethod.POST)
	@ResponseBody
	public ActionResult login(
			@RequestParam(value="sequence", required = false) String sequence,
			@RequestParam(value="loginName", required = false ,  defaultValue = "") String loginName,
			@RequestParam(value="loginPwd", required = false) String loginPwd,
			@RequestParam(value="os", required = false) String os
			){
		
		logger.info("Login api enter");
		logger.info("loginName:"+loginName);
		logger.info("regPwd:"+loginPwd);
		User user=accountService.findUserByLoginNameAndDelflag(loginName);
//		User user = this.accountService.findUserByLoginName(loginName);
		
		// 用户不存在
		if (null == user){
			return new ActionResult(sequence, Const._INT_FALSE, "", Const._FAIL_NO_UESR, null);
		}
		
		// 密码错误
		if (!this.accountService.login(user, loginPwd) ){
			return new ActionResult(sequence, Const._INT_FALSE, "", Const._FAIL_LOGIN_AUTH, null);
		}
		
		// 生成token并保存到数据库
		Token token = tokenService.newToken(user, loginName);
		
		// 这里返回user信息
	//	Cert cert = authService.findByUserById(user.getId());
		UserDTO dto = new UserDTO(token);
		/*if (cert!=null) {
			dto.setCertStatus(cert.getStatus().name());
		}*/
		//System.out.println(new ActionResult( sequence, Const._INT_TRUE, "", Const._OK_LOGIN,  dto ));
		return new ActionResult( sequence, Const._INT_TRUE, "", Const._OK_LOGIN,  dto );
	}
	
	// 模拟stateless验证
	@RequestMapping(value="authc", method = RequestMethod.POST)
	@ResponseBody
	public ActionResult authc(
			@RequestParam(value="sequence", required = false) String sequence
			){
		String username = accountService.getCurrentUser().getLoginName();
		return new ActionResult( sequence, Const._INT_TRUE, "", Const._OK_LOGIN,  username );
	}
/*
	// 获取个人资料 
	@RequestMapping(value="userinfo", method = RequestMethod.GET)
	@ResponseBody
	public ActionResult userinfo(
			@RequestParam(value="sequence", required = false) String sequence
			){
		User user = accountService.findCurrentUser();
		Cert cert = authService.findByUserById(user.getId());
		UserDTO dto = new UserDTO(user);
		if (cert!=null) {
			dto.setCertStatus(cert.getStatus().name());
		}
		return new ActionResult( sequence, Const._INT_TRUE, "", Const._OK_LOGIN, dto);
	}
	*/
	/**
	 * 新用户注册
	 * @author wendel 
	 * @param loginName
	 * @param regPwd
	 * @return
	 * @throws ParseException 
	 */
	 @RequestMapping(value="register.action",method = RequestMethod.POST)
	 @ResponseBody
	 public ActionResult register(
			@RequestParam(value="loginName", required = false) String loginName,
			@RequestParam(value="regPwd", required = false) String regPwd
		//	@RequestParam(value="authcode", required = true) String authcode,
		//	@RequestParam(value="registerType", required = true) String registerType
			) throws ParseException{
		 //是否存在user
//		 User existUser=this.accountService.findUserByLoginName(loginName);

		 logger.info("Register api enter");
		 logger.info("loginName:"+loginName);
		 logger.info("regPwd:"+regPwd);
		 //校验是否存在user
		 User existUser=accountService.findUserByLoginNameAndDelflag(loginName);
		 if(null!=existUser){
			 return new ActionResult( "", Const._INT_FALSE, "", Const._MOBILPHONE_EXISTS,"" );
		 }
	/*	 //比对验证码
		 String authResult=authcodeService.check(loginName,authcode,AuthcodeTypeEnum.register);
		 logger.info("authResult:"+authResult);
		 if (StringUtils.isNotBlank(authResult)){
			 return new ActionResult( "", Const._INT_FALSE, "", Const._FAIL_AUTHCODE_NO_EXISTS,"" );
		 }*/

		 User user = new User();
		 user.setLoginName(loginName);
		 user.setPlainPassword(regPwd);
		/* if(StringUtils.isNotBlank(registerType)){
			 user.setRegisterType(RegisterTypeEnum.valueOf(registerType));
			 logger.info("registerType:"+registerType);
		 }*/
		 accountService.registerUser(user);
		  //发送邮件
	//	 messageService.registerappemail(user);
		 
		 return new ActionResult( "", Const._INT_TRUE, "", Const._MOBILPHONE_SUCCESS,"" );
	 }
	 
	/**
	  * 重设密码
	  * @author wendel
	  * @param loginName
	  * @param regPwd
	  * @return
	  *//*
	 @RequestMapping(value="reset",method = RequestMethod.POST)
	 @ResponseBody
	 public ActionResult reset(
		@RequestParam(value="loginName", required = true) String loginName,
		@RequestParam(value="resetPwd", required = true) String resetPwd
		){
		 // 查找当前的用户
		 User user=this.accountService.findUserByLoginNameAndDelflag(loginName);;
		 logger.info("user:"+loginName);
		 // 更改密码
		 accountService.resetPassword(user,resetPwd,loginName);
		 return new ActionResult( "", Const._INT_TRUE, "", Const._OK_UP_PASS,"" );
	 }
	 
	 *//**
	  * 验证码比对
        * @author wendel		
        * @param loginName
        * @param authcode
        * @return
        *//*
	 @RequestMapping(value="check",method = RequestMethod.POST)
	 @ResponseBody
	 public ActionResult check(
			 @RequestParam(value="loginName", required = true) String loginName,
			 @RequestParam(value="authcode", required = true) String authcode
			 ){
		 // 比对验证码
		 String authResult=authcodeService.check(loginName,authcode,AuthcodeTypeEnum.resetpass);
		 logger.info("authResult:-"+authResult);
		 if(authResult==null){
			 return new ActionResult( "", Const._INT_TRUE, "", Const._FAIL_AUTHCODE_NO_EXISTS,"" );
		 }else{
			 return new ActionResult( "", Const._INT_FALSE, "", Const._SUCCESS_AUTHCODE_COMPARE,"" );
		 }
	 }*/
}